package com.zxl.yjb.activity.nearby;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.order.SosDetailActivity;
import com.zxl.yjb.adapter.NearbyHelpListAdapter;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.FileUploadBean;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.NearbyHelpBean;
import com.zxl.yjb.bean.VoiceUploadBean;
import com.zxl.yjb.fragment.near.MultifunctionalInputFragment;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;
import com.zxl.yjb.widget.EaseVoiceRecorderView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NearbyActivity extends BaseActivity implements View.OnClickListener, OnRefreshLoadMoreListener {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.voice_recorder)
    EaseVoiceRecorderView voiceRecorderView;
    MultifunctionalInputFragment inputFragment;
    @BindView(R.id.iv_confirm2)
    ImageView ivConfirm;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private ImageView ivBack;
    private DataManager dataManager;
    private LocationBean locationBean;
    private LoginSucessBean loginSucessBean;
    private int currentPager = 1;
    private int pageSize = 30;
    private NearbyHelpListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nearby);
        ButterKnife.bind(this);
        loginSucessBean = (LoginSucessBean) SaveBeanUtil.getBean(this, Const.VIPINFO);
        locationBean = (LocationBean) SaveBeanUtil.getBean(this, Const.LOCATION_LNGLAT);
        initView();
        refreshLayout.setOnRefreshLoadMoreListener(this);
        getSOSList();

    }


    @Override
    protected void initView() {
        recyclerview = findViewById(R.id.recyclerview);
        TextView tvPageTitle = findViewById(R.id.tv_page_title);
        ivBack = findViewById(R.id.iv_back);

        ivConfirm.setVisibility(View.VISIBLE);
        tvConfirm.setVisibility(View.VISIBLE);
        ivConfirm.setImageResource(R.mipmap.zy_lsdz);
        tvConfirm.setText("历史求助");
        tvConfirm.setTextColor(getResources().getColor(R.color.common_text_color));

        setAdapter();
        initFragment(voiceRecorderView);
        tvPageTitle.setText("附近求助");
        initEvent();
    }

    private void initEvent() {
        ivBack.setOnClickListener(this);
    }

    private void initFragment(EaseVoiceRecorderView voiceRecorderView) {
        FragmentManager manager = getSupportFragmentManager();
        inputFragment = (MultifunctionalInputFragment) manager.findFragmentById(R.id.input_fragment);
        inputFragment.bindVoiceRecorderView(voiceRecorderView);
        inputFragment.setOnInputViewItemClickListener(new MultifunctionalInputFragment.OnInputCompleteListener() {
            @Override
            public void onSubmitButtonClick(String content, List imgPath, String voiceFilePath) {
                if (imgPath != null && imgPath.size() != 0 && !TextUtils.isEmpty(voiceFilePath)) {
                    uploadPic(content, imgPath, voiceFilePath);
                } else if (imgPath != null && imgPath.size() != 0) {
                    uploadPic(content, imgPath, "");
                } else if (!TextUtils.isEmpty(voiceFilePath)) {
                    uploadVoice(content, "", voiceFilePath);
                } else if (!TextUtils.isEmpty(content)) {
                    sendSOS(content, "", "");
                }
            }
        });
    }

    private void setAdapter() {
        adapter = new NearbyHelpListAdapter(R.layout.nearbyhelp_item);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                NearbyHelpBean item = (NearbyHelpBean) adapter.getItem(position);
                startActivity(new Intent(NearbyActivity.this, SosDetailActivity.class)
                        .putExtra("id", item.getId() + ""));
            }
        });
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                int uid = ((NearbyHelpBean) adapter.getItem(position)).getUid();
                if (uid == loginSucessBean.getUid()) {
                    DisplayUtil.diaplayDialog(NearbyActivity.this, "提示", "确定要删除此信息吗？", "取消", "删除", null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            del(((NearbyHelpBean) adapter.getItem(position)).getId() + "", position);
                        }
                    });
                }

                return true;
            }
        });
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        recyclerview.setAdapter(adapter);

    }

    private void del(String id, final int position) {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                adapter.remove(position);
                adapter.notifyDataSetChanged();
            }
        };
        dataManager.sosdel(new ProgressObserver<Object>(listener, NearbyActivity.this), map);
    }

    private void getSOSList() {
        Map<String, String> map = new HashMap<>();
        map.put("page", currentPager + "");
        map.put("count", pageSize + "");
        dataManager = new DataManager();
        ObserverOnNextListener<List<NearbyHelpBean>> listener = new ObserverOnNextListener<List<NearbyHelpBean>>() {
            @Override
            public void onNext(List<NearbyHelpBean> detailBeanList) {
                if (currentPager++ == 1) {
                    adapter.setNewData(detailBeanList);
                    refreshLayout.finishRefresh();
                } else {
                    adapter.addData(detailBeanList);
                    refreshLayout.finishLoadMore();
                    if (detailBeanList.size() < pageSize) {
                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                }
            }
        };
        dataManager.sosList(new ProgressObserver<List<NearbyHelpBean>>(listener, this) {
            @Override
            public void showDialog() {
            }
        }, map);
    }


    private void sendSOS(String content, String imgUrls, String voice) {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("lon", locationBean.getLng() + "");
        map.put("lat", locationBean.getLat() + "");
        map.put("phone", loginSucessBean.getPhone() + "");
        map.put("text", content);
        map.put("voice", voice);
        map.put("picture", imgUrls);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object object) {
                ToastUtils.show(getApplicationContext(), "求助成功");
                inputFragment.clearMsg();
                onRefresh(refreshLayout);
            }
        };
        dataManager.sosHelp(new ProgressObserver<Object>(listener, this), map);
    }

    private void uploadPic(final String content, final List<LocalMedia> imgPath, final String voiceFilePath) {
        dataManager = new DataManager();
        ObserverOnNextListener<FileUploadBean> listener = new ObserverOnNextListener<FileUploadBean>() {
            @Override
            public void onNext(FileUploadBean fileUploadBean) {
                String imgUrls = haneldPicPath(fileUploadBean);
                if (!TextUtils.isEmpty(voiceFilePath)) {
                    uploadVoice(content, imgUrls, voiceFilePath);
                } else {
                    sendSOS(content, imgUrls, "");
                }

            }
        };
        dataManager.uploadMultiPicture(new ProgressObserver<FileUploadBean>(listener, this), imgPath);
    }


    private void uploadVoice(final String content, final String imgUrls, final String voiceFilePath) {
        dataManager = new DataManager();
        ObserverOnNextListener<VoiceUploadBean> listener = new ObserverOnNextListener<VoiceUploadBean>() {
            @Override
            public void onNext(VoiceUploadBean voiceUploadBean) {
                String Voice = voiceUploadBean.getYy_url();
                sendSOS(content, imgUrls, Voice);
            }
        };
        dataManager.uploadVoice(new ProgressObserver<VoiceUploadBean>(listener, this), voiceFilePath);
    }

    private String haneldPicPath(FileUploadBean fileUploadBean) {
        String picture = "";
        ArrayList<String> picList = fileUploadBean.getUrls();
        if (picList != null && picList.size() > 0)
            for (int i = 0; i < picList.size() - 1; i++) {
                picture += picList.get(i) + ",";
            }
        picture += picList.get(picList.size() - 1);
        return picture;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    inputFragment.onActivityResult(requestCode, resultCode, data);
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(5000);
        getSOSList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh(5000);
        currentPager = 1;
        getSOSList();
        refreshLayout.setNoMoreData(false);
    }

    @OnClick({R.id.iv_confirm, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_confirm:
            case R.id.tv_confirm:
                Intent intent = new Intent(NearbyActivity.this,NearbyHistoryActivity.class);
                startActivity(intent);
                break;
        }
    }
}
